package com.geek.novel.utils

import android.text.TextUtils
import com.geek.novel.common.Constant

/**
 * 书本相关的工具
 */
object BookUtil {

    /**格式化书名*/
    fun formatBookName(bookName: String?): String{
        val result = bookName?:""
        return removeAllHtmlTag(result)
    }

    /**格式化作者名*/
    fun formatAuthorName(authorName: String?): String{
        val result = authorName?:""
        return removeAllHtmlTag(result)
    }

    /**把书籍描述中的<br>替换成换行符*/
    fun formatBookDescBlank(desc: String?): String{
        return replaceBookDescBlank(desc, "\r\n")
    }

    /**去掉书籍描述中的<br>*/
    fun removeBookDescBlank(desc: String?): String{
        return replaceBookDescBlank(desc, "")
    }

    private fun replaceBookDescBlank(desc: String?, target: String): String{
        if(FormatUtil.isEmpty(desc)){
            return ""
        }
        //匹配<br>换行符
        val br = Regex("(<br.*?/?>)+")
        var result = desc!!.replace(br, target)

        val map = getCommonDescRegex()
        map.forEach { (key, value) ->
            result = result.replace(Regex(key), value)
        }

        //干掉所有script标签
        result = replaceContent(result, Constant.REGEX_MATCH_SCRIPT)
        //干掉所有标签
        result = replaceContent(result, Constant.REGEX_MATCH_ALL_TAG)

        return result
    }

    /**通用的正则匹配规则*/
    private fun getCommonDescRegex(): Map<String, String>{
        val params = HashMap<String, String>()
        //匹配下划线等特殊字符
        params["_{3,}"] = ""
        //替换掉nbsp;为空格
        params["nbsp;"] = " "
        //替换掉 来源：到斜杆结尾的 几个字
        params["来源：.+/"] = ""
        return params
    }


    /**
     * 替换规则
     * ["a:b","c:d"]
     * 表示把a替换成b，把c替换成d；替换的key支持正则
     */
    fun replaceContent(content: String, rule: String?): String{
        if(TextUtils.isEmpty(rule)){
            return content
        }
        val index = rule!!.lastIndexOf(":")
        var key = rule
        var value = ""
        if(index > -1){
            key = rule.substring(0, index)
            value = rule.substring(index+1)
        }
        return content.replace(Regex(key), value)
    }

    /**移除所有html标签*/
    fun removeAllHtmlTag(content: String): String{
        var result = content
        //干掉所有script标签
        result = replaceContent(result, Constant.REGEX_MATCH_SCRIPT)
        //干掉所有标签
        result = replaceContent(result, Constant.REGEX_MATCH_ALL_TAG)
        //去掉特殊字符
        result = replaceContent(result, "\uFEFF:")
        //多个换行变成一个
        result = replaceContent(result, "\n+:\n")
        //移除开头和结尾的/n
        result = replaceContent(result, "^\\s+:")
        result = replaceContent(result, "\\s+$:")
        //移除前后空格
        result = result.trim()

        return result
    }

}